/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.util;

import org.apache.commons.lang.StringUtils;

import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.util.ResourceBundle;
import java.util.List;
import java.util.ArrayList;

public class DicewareGenerator {
  private ResourceBundle words;
  private int numWords;
  private KeyGenerator keyGenerator;

  public DicewareGenerator() {
    this(3);
  }

  public DicewareGenerator(int numWords) {
    this(numWords, new KeyGenerator() {
      SecureRandom random;

      {
        try {
          random = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
          throw new RuntimeException(e);
        }
      }

      public String generateKey() {
        StringBuilder key = new StringBuilder();
        for (int i = 0; i < 5; i++) {
          key.append(random.nextInt(6) + 1);
        }
        return key.toString();
      }
    });
  }

  public DicewareGenerator(int numWords, KeyGenerator keyGenerator) {
    this.keyGenerator = keyGenerator;
    this.words = ResourceBundle.getBundle("diceware");
    this.numWords = numWords;
  }

  public String generate() {
    List<String> words = new ArrayList<String>(numWords);
    for (int i = 0; i < numWords; i++) {
      String wordKey = keyGenerator.generateKey();
      words.add(this.words.getString(wordKey));
    }
    return StringUtils.join(words.iterator(), ' ');
  }

  public static interface KeyGenerator {
    String generateKey();
  }

  public static void main(String[] args) {
    DicewareGenerator generator = new DicewareGenerator(new Integer(args[0]));
    for(int i = 0; i < 10; i++) {
      System.out.println(generator.generate());
    }
  }
}